
Ext.ns('X.column');

//---------------------------//
//       X.column.Text       //
//---------------------------//

X.column.Text = Ext.extend(Ext.grid.Column, {
    editor   : new X.field.Text(),
    sortable : true,
    align    : 'left'
});

//-----------------------------//
//       X.column.Number       //
//-----------------------------//

X.column.Number = Ext.extend(Ext.grid.NumberColumn, {
    editor   : new X.field.Number(),
    sortable : true,
    align    : 'right',
    format   : '0.000/i'
});

//----------------------------//
//       X.column.Money       //
//----------------------------//

X.column.Money = Ext.extend(Ext.grid.NumberColumn, {
    editor   : new X.field.Number(),
    sortable : true,
    align    : 'right',
    format   : '0.000 Gs/i'
});

//---------------------------//
//       X.column.Date       //
//---------------------------//

X.column.Date = Ext.extend(Ext.grid.Column, {
    editor   : new X.field.Date(),
    sortable : true,
    align    : 'left',
    renderer : function(val){

        if (!val)                return '';
        if (val instanceof Date) return val.format('d/m/Y');

        try{
            return Date.parseDate(val, 'Y-m-d').format('d/m/Y');
        }catch(e){try{
            return Date.parseDate(val, 'Y-m-d H:i:s').format('d/m/Y');
        }catch(e){
            X.msg.FailureJs(e.message);
        }}
    }
});

//---------------------------//
//     X.column.DateTime     //
//---------------------------//

X.column.DateTime = Ext.extend(Ext.grid.Column, {
    editor   : new X.field.Date(),
    sortable : true,
    align    : 'left',
    renderer : function(val){

        if (!val)                return '';
        if (val instanceof Date) return val.format('d/m/Y');

        try{
            return Date.parseDate(val, 'Y-m-d').format('d/m/Y');
        }catch(e){ try{
            return Date.parseDate(val, 'Y-m-d H:i:s').format('d/m/Y H:i:s');
        }catch(e){
            X.msg.FailureJs(e.message);
        }}
    }
});

//----------------------------//
//       X.column.Combo       //
//----------------------------//

X.column.Combo = Ext.extend(Ext.grid.Column, {
    sortable : true,
    align    : 'left',
    renderer : function(value){
            var record = this.editor.findRecord(this.editor.valueField, value);
            return record ? record.get(this.editor.displayField) : this.editor.valueNotFoundText;
    }
});

//----------------------------//
//       X.column.Import      //
//----------------------------//


X.column.Import = Ext.extend(Ext.grid.ActionColumn, {
    width        : 28,
    menuDisabled : true,

    constructor: function(cfg) {

        cfg.items =
        [{
            icon    : '/img/icon_importar.png',
            tooltip : 'Importar',
            handler : function(grid, rowIndex, colIndex)
            {
                var rec = grid.getStore().getAt(rowIndex);

                // mensaje de confirmacion
                Ext.Msg.show
                ({
                    title   : 'Confirmar',
                    msg     : 'Está seguro que desea importar ' + this.msgName + ' "' + rec.get(this.msgNameCol) + '"?',
                    buttons :  {yes: 'Sí', no: 'No'},
                    fn      : function(btn, text)
                    {
                        // elige YES
                        if (btn == 'yes')
                        {
                            try{

                                window.location = this.importUrl + '?id=' + rec.get(this.idColumn);
                            }
                            catch(e){
                                    X.msg.FailureJs(e.message);
                            }
                        }
                    }.bind(this)
                    // fin Ext.Msg.show.fn
                });
                // fin Ext.Msg.show
            }
            //fin handler
        }];
        // fin items

        X.column.Edit.superclass.constructor.call(this, cfg);
    }
});


//---------------------------//
//       X.column.Hidden       //
//---------------------------//

X.column.Hidden = Ext.extend(Ext.grid.Column, {
    editor   : new X.field.Hidden(),
    sortable : false,
    hidden  : true
});


//----------------------------//
//        X.column.Edit       //
//----------------------------//

//  controller  : nombre del controlador a llamar por ajax
//  idColumn    : id del objecto a eliminar

X.column.Edit = Ext.extend(Ext.grid.ActionColumn, {
    width        : 28,
    menuDisabled : true,
    constructor  : function(cfg) {

        cfg.items =
        [{
            icon    : '/img/icon_editar.png',
            tooltip : 'Editar',
            handler : function(grid, rowIndex, colIndex)
            {
                try{
                    var rec = grid.getStore().getAt(rowIndex);
                    window.location = this.editUrl + '?id=' + rec.get(this.idColumn);
                }
                catch(e){
                    X.msg.FailureJs(e.message);
                }
            }
        }];

        X.column.Edit.superclass.constructor.call(this, cfg);
    }
});

//----------------------------//
//       X.column.Delete      //
//----------------------------//

//  controller : nombre del controlador a llamar por ajax
//  idColumn   : columna que contiene el id
//  msgName    : Está seguro de eliminar el "[msg_name]" "[msg_namecol]"?
//  msgNameCol : Está seguro de eliminar el "[msg_name]" "[msg_namecol]"?

X.column.Delete = Ext.extend(Ext.grid.ActionColumn, {
    width        : 28,
    menuDisabled : true,

    constructor: function(cfg) {

        cfg.items =
        [{
            icon    : this.customIcon?this.customIcon:'/img/icon_eliminar.png',
            tooltip : this.customTooltip?this.customTooltip:'Eliminar',
            handler : function(grid, rowIndex, colIndex)
            {
                var rec = grid.getStore().getAt(rowIndex);

                // mensaje de confirmacion
                Ext.Msg.show
                ({
                    title   : 'Confirmar',
                    msg     : this.customMsg?this.customMsg:'Está seguro de eliminar ' + this.msgName + ' "' + rec.get(this.msgNameCol) + '"?',
                    buttons : Ext.Msg.YESNO,
                    fn      : function(btn, text)
                    {
                        // elige YES
                        if (btn == 'yes')
                        {
                            // envio ajax
                            Ext.Ajax.request({
                                url     : this.customUrl?this.customUrl:this.deleteUrl,
                                method  : 'POST',
                                params  : {id : rec.get(this.idColumn)},

                                // ajax.success
                                success : function (result, request){
                                    try{
                                        var obj = Ext.util.JSON.decode(result.responseText);
                                        if (obj.success){
                                            X.msg.SuccessReload(obj.msg, grid);
                                            
                                        }
                                        else{
                                            X.msg.Failure(obj.msg);
                                        }
                                    }
                                    catch(e){
                                        X.msg.FailureJs(e.message);
                                    }
                                }.bind(this),

                                // ajax.failure
                                failure : function (result, request){
                                    X.msg.Failure(this.customMsgFailure?this.customMsgFailure:'Error al eliminar el ' + this.msgName + '.');
                                }
                            });
                        }
                    }.bind(this)
                    // fin Ext.Msg.show.fn
                    
                });
                // fin Ext.Msg.show
            }
            //fin handler
        }];
        // fin items     

        X.column.Edit.superclass.constructor.call(this, cfg);
    }
});

X.column.Validate = Ext.extend(X.column.Delete, {
    customIcon: '/img/icon_validar.png',
    customTooltip: 'Confirmar Solicitud',
    customMsg:  '¿Está seguro de que desea confirmar la solicitud?',
    customMsgFailure:'Error al confirmar la solicitud'
});

X.column.View = Ext.extend(Ext.grid.ActionColumn, {
    width        : 28,
    menuDisabled : true,
    constructor  : function(cfg) {

        cfg.items =
        [{
            icon    : '/img/icon_ver.png',
            tooltip : 'Ver',
            handler : function(grid, rowIndex, colIndex)
            {
                try{
                     var rec = grid.getStore().getAt(rowIndex);
                     new Ext.ux.MediaWindow({
                        id        : 'PDFViewerWin',
                        title     : 'PDF',
                        bodyStyle : 'position:relative; padding:0px;',
                        width     : 1024,
                        height    : 650,
                        mediaCfg  : {
                            mediaType       : 'PDF',
                            url             : this.ViewUrl +'?id='+rec.get(this.idColumn),
                            unsupportedText : 'Acrobat Viewer is not Installed',
                            resizable       : true
                        }
                    }).show();
                   
                }
                catch(e){
                    X.msg.FailureJs(e.message);
                }
            }
        }]

        X.column.View.superclass.constructor.call(this, cfg);
    }
});

//-------------------------------//
//        X.grid.GridPanel       //
//-------------------------------//

Ext.ns('X.grid');

X.grid.GridPanel = Ext.extend(Ext.grid.GridPanel, {

    renderTo     : 'layout_content',
    style        : 'margin:auto; textAlign:left;',
    stripeRows   : true,
    loadMask     : true,
    monitorValid : true,

    initComponent : function() {

         this.store.submitFieldId = this.id + 'Rows';
        
        
         if (this.useBbar == undefined || this.useBbar == true)
        // PagingToolbar
        this.bbar = new Ext.PagingToolbar({
            pageSize    : 20,
            store       : this.store,
            buttonAlign : 'center'
        });

        // super class constructor
        X.grid.GridPanel.superclass.initComponent.call(this);
    }
});

//--------------------------------//
//        X.grid.GridEditor       //
//--------------------------------//

X.grid.GridEditor = Ext.extend(Ext.grid.EditorGridPanel, {

    renderTo     : 'layout_content',
    style        : 'margin:auto; textAlign:left;',
    stripeRows   : true,
    loadMask     : true,
    monitorValid : true,
    sm           : new Ext.grid.RowSelectionModel(),

    initComponent : function() {

        // creado por       : this
        // es utilizado por : this.store
        // para             : conocer el id del X.field al que se va a almacenar los rows para el submit
        this.store.submitFieldId = this.id + 'Rows';

        // sort local
        this.store.remoteSort = false;


        // toolbar
        if (this.useTbar == undefined || this.useTbar == true)

        this.tbar = [{
            // boton agregar
            text: 'Agregar',
            icon:'/img/icon_agregar.png',
            handler : function(){
                try{
                    this.stopEditing();
                    /*
                    if (!this.store.getAt(0) || this.store.getAt(0).modified){
                        this.store.insert(0, new this.store.recordType({}));
                    }*/
                    this.store.insert(0, new this.store.recordType({}));
                    this.startEditing(0, 0);
                    this.sm.selectRow(0);
                }
                catch(e){
                    X.msg.FailureJs(e.message);
                }
            }.bind(this)
        },'-',{
            // boton quitar
            id: 'sacar',
            text: 'Quitar',
            icon:'/img/icon_eliminar.png',
            handler : function(){
                try{
                    var record = this.sm.getSelected();
                    if (record) {
                        var index = this.store.indexOf(record);
                        this.store.removeAt(index);

                        if (index < this.store.getCount())
                            this.sm.selectRow(index);
                        else
                            this.sm.selectRow(index-1);
                    }
                }
                catch(e){
                    X.msg.FailureJs(e.message);
                }
            }.bind(this)
        }];

        // super class constructor
        X.grid.GridEditor.superclass.initComponent.call(this);
    }
});